package com.neusoft.bizcore.auth.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.auth.model.AuthUser;
import com.neusoft.bizcore.auth.model.QAuthUser;
import com.neusoft.bizcore.auth.repository.CustomizedAuthUserRepository;
import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedAuthUserRepositoryImpl extends AbstractRepository
        implements CustomizedAuthUserRepository {

    @Override
    public Page<AuthUser> search(final Pageable pageable, final Searchable searchable) {
        final QAuthUser qAuthUser = QAuthUser.authUser;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AuthUser> query = this.query().selectFrom(qAuthUser);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    public List<AuthUser> search(final Searchable searchable) {
        final QAuthUser qAuthUser = QAuthUser.authUser;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AuthUser> query = this.query().selectFrom(qAuthUser);
        query.where(where);

        return query.fetch();
    }

    @Override
    protected Class<?> getModelClass() {
        return AuthUser.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QAuthUser qAuthUser = QAuthUser.authUser;

        where.and(super.containsStr(qAuthUser.username, searchable, "username"));
        where.and(super.containsStr(qAuthUser.name, searchable, "name"));
        final BooleanBuilder whereGlobal = new BooleanBuilder();
        if (!StringUtils.isEmpty(searchable.getStrValue("orgCode"))) {
        	whereGlobal.or(super.equalsStr(qAuthUser.oganizations.any().code, searchable, "orgCode"));
        }
        if (searchable.hasKey("orgCodes")) {
        	whereGlobal.or(super.inStrings(qAuthUser.oganizations.any().code, searchable, "orgCodes"));
        }
        where.and(whereGlobal);

        where.and(super.equalsStr(qAuthUser.roles.any().code, searchable, "roleCode"));

        if (searchable.hasKey("roleCodeArray")) {
            where.and(super.inStrings(qAuthUser.roles.any().code, searchable, "roleCodeArray"));
        }

        return where;
    }

}
